<template>
  <view class="verify-container">
    <!-- 快捷操作区 -->
    <view class="quick-actions">
      <view class="action-card scan-card" @click="scanVerify">
        <view class="action-icon">
          <uni-icons type="scan" size="32" color="#fff" />
        </view>
        <text class="action-title">扫码核销</text>
        <text class="action-desc">扫描团购券二维码</text>
      </view>
      
      <view class="action-card manual-card" @click="manualVerify">
        <view class="action-icon">
          <uni-icons type="compose" size="32" color="#fff" />
        </view>
        <text class="action-title">手动核销</text>
        <text class="action-desc">输入核销码核销</text>
      </view>
    </view>

    <!-- 今日核销统计 -->
    <view class="today-stats">
      <text class="stats-title">今日核销统计</text>
      <view class="stats-grid">
        <view class="stats-item">
          <text class="stats-value">{{ todayStats.verifyCount }}</text>
          <text class="stats-label">核销数量</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">¥{{ formatPrice(todayStats.verifyAmount) }}</text>
          <text class="stats-label">核销金额</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">{{ todayStats.verifyUsers }}</text>
          <text class="stats-label">核销用户</text>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <uni-search-bar 
        v-model="searchKeyword" 
        placeholder="搜索订单号或用户名"
        @confirm="handleSearch"
        @clear="handleClearSearch"
      />
    </view>

    <!-- 核销记录列表 -->
    <scroll-view 
      class="verify-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <view 
          class="verify-card"
          v-for="record in verifyRecords"
          :key="record.id"
          @click="viewDetail(record)"
        >
          <!-- 记录头部 -->
          <view class="record-header">
            <view class="record-info">
              <text class="order-no">{{ record.orderNo }}</text>
              <text class="verify-time">{{ formatTime(record.verifyTime) }}</text>
            </view>
            <view class="verify-status">
              <uni-tag text="已核销" type="success" size="small" />
            </view>
          </view>

          <!-- 记录内容 -->
          <view class="record-body">
            <view class="user-info">
              <view class="user-avatar">
                <uni-icons type="person-filled" size="20" color="#999" />
              </view>
              <view class="user-details">
                <text class="username">{{ record.username }}</text>
                <text class="order-amount">¥{{ formatPrice(record.orderAmount) }}</text>
              </view>
            </view>
            
            <view class="verify-info">
              <view class="info-item">
                <uni-icons type="shop" size="14" color="#999" />
                <text class="info-text">{{ record.storeName }}</text>
              </view>
              <view class="info-item">
                <uni-icons type="person" size="14" color="#999" />
                <text class="info-text">{{ record.operatorName }}</text>
              </view>
            </view>
          </view>

          <!-- 备注信息 -->
          <view class="record-remark" v-if="record.remark">
            <text class="remark-text">备注：{{ record.remark }}</text>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <uni-load-more :status="loadStatus" />
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && verifyRecords.length === 0">
          <image class="empty-image" src="/static/images/empty-verify.png" />
          <text class="empty-text">暂无核销记录</text>
          <button class="empty-btn" @click="scanVerify">开始核销</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { verifyApi } from '@/api/groupbuy';
import type { VerifyRecord, VerifyQuery } from '@/types/groupbuy';

// 响应式数据
const verifyRecords = ref<VerifyRecord[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 今日统计数据
const todayStats = ref({
  verifyCount: 0,
  verifyAmount: 0,
  verifyUsers: 0,
});

// 加载状态
const loadStatus = computed(() => {
  if (loading.value) return 'loading';
  if (!hasMore.value) return 'noMore';
  return 'more';
});

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 加载核销记录列表
const loadVerifyRecords = async (reset = false) => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    
    if (reset) {
      currentPage.value = 1;
      hasMore.value = true;
    }

    const params: VerifyQuery = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    const res = await verifyApi.getList(params);
    
    if (res.success) {
      const newList = res.data.list || [];
      
      if (reset) {
        verifyRecords.value = newList;
      } else {
        verifyRecords.value.push(...newList);
      }
      
      hasMore.value = newList.length === pageSize.value;
      
      if (!reset) {
        currentPage.value++;
      }
    } else {
      uni.showToast({
        title: res.message || '加载失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('加载核销记录失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 加载今日统计
const loadTodayStats = async () => {
  try {
    // 模拟今日统计数据
    todayStats.value = {
      verifyCount: 28,
      verifyAmount: 156800, // 分
      verifyUsers: 25,
    };
  } catch (error) {
    console.error('加载今日统计失败:', error);
  }
};

// 扫码核销
const scanVerify = () => {
  uni.navigateTo({
    url: '/pages/groupons/verify/new?type=scan',
  });
};

// 手动核销
const manualVerify = () => {
  uni.navigateTo({
    url: '/pages/groupons/verify/new?type=manual',
  });
};

// 搜索
const handleSearch = () => {
  loadVerifyRecords(true);
};

// 清除搜索
const handleClearSearch = () => {
  searchKeyword.value = '';
  loadVerifyRecords(true);
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  Promise.all([
    loadVerifyRecords(true),
    loadTodayStats(),
  ]).finally(() => {
    refreshing.value = false;
  });
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadVerifyRecords();
  }
};

// 查看详情
const viewDetail = (record: VerifyRecord) => {
  uni.navigateTo({
    url: `/pages/groupons/verify/detail?id=${record.id}`,
  });
};

// 页面加载
onMounted(() => {
  loadTodayStats();
  loadVerifyRecords(true);
});
</script>

<style lang="scss" scoped>
.verify-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.quick-actions {
  display: flex;
  gap: 16rpx;
  padding: 24rpx 32rpx;
  
  .action-card {
    flex: 1;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;
    
    &.scan-card {
      background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
    }
    
    &.manual-card {
      background: linear-gradient(135deg, #52C41A 0%, #73D13D 100%);
    }
    
    .action-icon {
      margin-bottom: 16rpx;
    }
    
    .action-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #fff;
      margin-bottom: 8rpx;
    }
    
    .action-desc {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
    }
    
    &:active {
      transform: scale(0.98);
    }
  }
}

.today-stats {
  background: #fff;
  margin: 0 32rpx 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .stats-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .stats-grid {
    display: flex;
    
    .stats-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stats-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #1890FF;
        margin-bottom: 8rpx;
      }
      
      .stats-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-section {
  padding: 0 32rpx 24rpx;
}

.verify-list {
  flex: 1;
  
  .list-content {
    padding: 0 32rpx 24rpx;
  }
}

.verify-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .record-info {
      .order-no {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .verify-time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
  
  .record-body {
    padding: 24rpx;
    
    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .user-avatar {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;
      }
      
      .user-details {
        flex: 1;
        
        .username {
          font-size: 28rpx;
          color: #333;
          display: block;
          margin-bottom: 4rpx;
        }
        
        .order-amount {
          font-size: 26rpx;
          font-weight: 600;
          color: #FF4D4F;
        }
      }
    }
    
    .verify-info {
      display: flex;
      gap: 32rpx;
      
      .info-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
        
        .info-text {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
  
  .record-remark {
    padding: 16rpx 24rpx;
    background: #f9f9f9;
    border-top: 1rpx solid #f0f0f0;
    
    .remark-text {
      font-size: 24rpx;
      color: #666;
      line-height: 1.4;
    }
  }
}

.load-more {
  padding: 32rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 32rpx;
  }
  
  .empty-btn {
    background: #1890FF;
    color: #fff;
    border: none;
    border-radius: 24rpx;
    padding: 16rpx 32rpx;
    font-size: 26rpx;
  }
}
</style>
